package com.xjrsoft.module.customer.erp_model.eRP_OutStock.service.impl;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.dbmodel.utils.DataSourceUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.customer.erp_model.eRP_OutStock.dto.ErpStockoutstockentryDto;
import com.xjrsoft.module.customer.erp_model.eRP_OutStock.entity.ErpStockoutstock;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjrsoft.module.customer.erp_model.eRP_OutStock.entity.ErpStockoutstockentry;
import com.xjrsoft.module.customer.erp_model.eRP_OutStock.mapper.ErpStockoutstockentryMapper;
import com.xjrsoft.module.customer.erp_model.eRP_OutStock.dto.ErpStockoutstockListDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;
import com.xjrsoft.module.customer.erp_model.eRP_OutStock.mapper.ErpStockoutstockMapper;
import com.xjrsoft.module.customer.erp_model.eRP_OutStock.service.IErpStockoutstockService;
import com.xjrsoft.core.mp.base.BaseService;
import com.xjrsoft.module.customer.erp_model.eRP_OutStock.vo.ErpStockoutstockentryVo;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.entity.ErpInventory;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.service.IErpInventoryService;
import com.xjrsoft.module.customer.erp_model.goodsManage.entity.ErpGoods;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import javax.annotation.Resource;

/**
 *  服务实现类
 *
 * @author pp
 * @since 2021-10-08
 */
@Service
@AllArgsConstructor
public class ErpStockoutstockServiceImpl extends BaseService<ErpStockoutstockMapper, ErpStockoutstock> implements IErpStockoutstockService {

	@Resource
	private ErpStockoutstockentryMapper erpStockoutstockentryMapper;

	private IErpInventoryService erpInventoryService;

	@Override
	public IPage<ErpStockoutstock> getPageList(ErpStockoutstockListDto pageListDto) {
		Wrapper<ErpStockoutstock> wrapper = Wrappers.<ErpStockoutstock>query().lambda()				.eq(!StringUtil.isEmpty(pageListDto.getF_OutStockCode()), ErpStockoutstock::getFOutstockcode, pageListDto.getF_OutStockCode())
				.ge(!StringUtil.isEmpty(pageListDto.getF_OutStockDate_Start()), ErpStockoutstock::getFOutstockdate, pageListDto.getF_OutStockDate_Start())
				.le(!StringUtil.isEmpty(pageListDto.getF_OutStockDate_End()), ErpStockoutstock::getFOutstockdate, pageListDto.getF_OutStockDate_End())
				.eq(!StringUtil.isEmpty(pageListDto.getF_WarehouseId()), ErpStockoutstock::getFWarehouseid, pageListDto.getF_WarehouseId());
		return this.page(ConventPage.getPage(pageListDto), wrapper);
	}

	public  String updateInfo(ErpStockoutstock erpStockoutstock, List<ErpStockoutstockentryDto> erpStockoutstockentryDtos) throws SQLException {
		boolean isNoQua=false;
		//判断库存是否足够
		for (int i=0;i<erpStockoutstockentryDtos.size();i++)
		{
			String sql1="select * from erp_inventory i where i.F_WareHouseId='"+erpStockoutstock.getFWarehouseid()+"'and i.F_GoodsId='"+erpStockoutstockentryDtos.get(i).getFGoodsid()+"'";
			List<Entity> inventoryList= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
			if(inventoryList.size()>0) {
				if (erpStockoutstockentryDtos.get(i).getFUnitid().equals(erpStockoutstockentryDtos.get(i).getFBasicunit())) {
					Integer amount = inventoryList.get(0).getInt("F_BasicAmount");
					if (erpStockoutstockentryDtos.get(i).getFQuantity().compareTo(amount) == 1) {
						isNoQua = true;
					}
				} else if (erpStockoutstockentryDtos.get(i).getFUnitid().equals(erpStockoutstockentryDtos.get(i).getFComunit())) {
					Integer amount = inventoryList.get(0).getInt("F_ComAmount");
					if (erpStockoutstockentryDtos.get(i).getFQuantity().compareTo(amount) > 0) {
						isNoQua = true;
					}
				} else {
					BigDecimal converTate = null;
					//查询转换率
					BigDecimal baseConverRate = null;
					//显示单位转换率
					BigDecimal comConverRate=null;
					String sql2 = "select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='" + erpStockoutstockentryDtos.get(i).getFUnitid() + "'";
					List<Entity> list = Db.use(DataSourceUtil.getDataSource("localDB")).query(sql2);
					for (int j = 0; j < list.size(); j++) {
						if (list.get(j).get("f_fullname").toString().equals(erpStockoutstockentryDtos.get(i).getFComunit().toString()))
						{
							comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpStockoutstockentryDtos.get(i).getFBasicunit().toString()))
						{
							baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					BigDecimal amount1 = inventoryList.get(0).getBigDecimal("F_BasicAmount");
					BigDecimal amount2 = inventoryList.get(0).getBigDecimal("F_ComAmount");
					if (new BigDecimal(erpStockoutstockentryDtos.get(i).getFQuantity()).multiply(baseConverRate).compareTo(amount1) >0 || new BigDecimal(erpStockoutstockentryDtos.get(i).getFQuantity()).multiply(comConverRate).compareTo(amount2) >0) {
						isNoQua = true;
					}
				}
			}
			else {
				isNoQua=true;
			}
		}
		if(isNoQua)
		{
			return "库存不足，请检查该仓库的商品库存";
		}
		for (int i=0;i<erpStockoutstockentryDtos.size();i++) {
			//入库单位和基本单位和库存显示单位都一样可以直接做操作  1.对库存做操作（新增或修改）
			if (erpStockoutstockentryDtos.get(i).getFBasicunit().equals(erpStockoutstockentryDtos.get(i).getFUnitid()) && erpStockoutstockentryDtos.get(i).getFComunit().equals(erpStockoutstockentryDtos.get(i).getFUnitid())) {
				String sql1 = "SELECT * FROM erp_inventory i where i.F_WarehouseId='" + erpStockoutstock.getFWarehouseid() + "' and i.F_GoodsId='" + erpStockoutstockentryDtos.get(i).getFGoodsid() + "'";
				List<Entity> isInventory1 = Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
				ErpInventory erpInventory1 = new ErpInventory();
				erpInventory1.setFGoodsid(erpStockoutstockentryDtos.get(i).getFGoodsid());
				erpInventory1.setFWarehouseid(erpStockoutstock.getFWarehouseid());
				//如果有的话就修改对应商品的库存
				if (isInventory1.size() > 0) {

					BigDecimal aftBasicQua = isInventory1.get(0).getBigDecimal("f_basicamount");
					BigDecimal aftComamQua = isInventory1.get(0).getBigDecimal("f_comamount");
					BigDecimal quantity = new BigDecimal(erpStockoutstockentryDtos.get(i).getFQuantity());
					erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
					erpInventory1.setFBasicamount(aftBasicQua.subtract(quantity));
					erpInventory1.setFComamount(aftComamQua.subtract(quantity));
					//怎么在一个serveimp里去调用另外一个里面的方法 一定要注入
					erpInventoryService.updateById(erpInventory1);
				}
			}
			//不一样先查询换算率得到之后转换
			else {
				//这里组合有四种情况  只有同时满足不相等的情况 才需要同时转换
				//基本单位转换率
				BigDecimal baseConverRate = null;
				//显示单位转换率
				BigDecimal comConverRate = null;
				if (!erpStockoutstockentryDtos.get(i).getFBasicunit().equals(erpStockoutstockentryDtos.get(i).getFUnitid()) && !erpStockoutstockentryDtos.get(i).getFComunit().equals(erpStockoutstockentryDtos.get(i).getFUnitid())) {
					//查询转换率
					String sql = "select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='" + erpStockoutstockentryDtos.get(i).getFUnitid() + "'";
					List<Entity> list = Db.use(DataSourceUtil.getDataSource("localDB")).query(sql);
					for (int j = 0; j < list.size(); j++) {
						if (list.get(j).get("f_fullname").toString().equals(erpStockoutstockentryDtos.get(i).getFComunit().toString())) {
							baseConverRate = new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpStockoutstockentryDtos.get(i).getFBasicunit().toString())) {
							comConverRate = new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					//得到转换率之后开始转换
					//根据商品id和仓库id查询是否有此商品的库存数据
					String sql1 = "SELECT * FROM erp_inventory i where i.F_WarehouseId='" + erpStockoutstock.getFWarehouseid() + "' and i.F_GoodsId='" + erpStockoutstockentryDtos.get(i).getFGoodsid() + "'";
					List<Entity> isInventory1 = Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
					ErpInventory erpInventory1 = new ErpInventory();
					BigDecimal quantity = new BigDecimal(erpStockoutstockentryDtos.get(i).getFQuantity());
					erpInventory1.setFWarehouseid(erpStockoutstock.getFWarehouseid());
					erpInventory1.setFGoodsid(erpStockoutstockentryDtos.get(i).getFGoodsid());
					//如果有的话就修改对应商品的库存
					if (isInventory1.size() > 0) {
						//修改数量=原有的数据+本次入库的数量*转换率
						erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
						BigDecimal aftBasicQua = isInventory1.get(0).getBigDecimal("f_basicamount");
						BigDecimal aftComamQua = isInventory1.get(0).getBigDecimal("f_comamount");
						erpInventory1.setFBasicamount(aftBasicQua.subtract(quantity.multiply(baseConverRate)));
						erpInventory1.setFComamount(aftComamQua.subtract(quantity.multiply(comConverRate)));
						erpInventoryService.updateById(erpInventory1);
					}
				} else {
					//其中一个需要转换 先判断是基本数量单位需要转换还是库存显示单位需要转换
					//如果库存显示单位和入库单位不相等 就需要转换,否则就是基本单位需要转换
					//先查询出转换率
					String sql = "select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='" + erpStockoutstockentryDtos.get(i).getFUnitid() + "'";
					List<Entity> list = Db.use(DataSourceUtil.getDataSource("localDB")).query(sql);

					for (int j = 0; j < list.size(); j++) {
						if (list.get(j).get("f_fullname").toString().equals(erpStockoutstockentryDtos.get(i).getFComunit().toString())) {
							comConverRate = new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpStockoutstockentryDtos.get(i).getFBasicunit().toString())) {
							baseConverRate = new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					//得到转换率之后开始转换
					//根据商品id和仓库id查询是否有此商品的库存数据
					String sql1 = "SELECT * FROM erp_inventory i where i.F_WarehouseId='" + erpStockoutstock.getFWarehouseid() + "' and i.F_GoodsId='" + erpStockoutstockentryDtos.get(i).getFGoodsid() + "'";
					List<Entity> isInventory1 = Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
					ErpInventory erpInventory1 = new ErpInventory();
					//本次入库数量
					BigDecimal quantuty = new BigDecimal(erpStockoutstockentryDtos.get(i).getFQuantity());
					erpInventory1.setFGoodsid(erpStockoutstockentryDtos.get(i).getFGoodsid());
					erpInventory1.setFWarehouseid(erpStockoutstock.getFWarehouseid());
					//修改数量=原有的数据-本次出库的数量*转换率
					//如果有的话就修改对应商品的库存
					if (isInventory1.size() > 0) {
						BigDecimal aftBasicQua = isInventory1.get(0).getBigDecimal("f_basicamount");
						BigDecimal aftComamQua = isInventory1.get(0).getBigDecimal("f_comamount");
						erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
						erpInventory1.setFComamount(aftComamQua.subtract(quantuty));
						erpInventory1.setFBasicamount(aftBasicQua.subtract(quantuty));
						//是否需要转换 需要的话就重新赋值
						if (!erpStockoutstockentryDtos.get(i).getFComunit().equals(erpStockoutstockentryDtos.get(i).getFUnitid())) {
							erpInventory1.setFComamount(aftComamQua.subtract(quantuty.multiply(comConverRate)));
						} else {
							erpInventory1.setFBasicamount(aftBasicQua.subtract(quantuty.multiply(baseConverRate)));
						}
						erpInventoryService.updateById(erpInventory1);
					}
				}
			}
		}
		return  null;
	}

	@SneakyThrows
	@Override
	public String addErpStockoutstock(ErpStockoutstock erpStockoutstock, List<ErpStockoutstockentryDto> erpStockoutstockentryDtos,List<ErpStockoutstockentry> erpStockoutstockentryList) {
		String isReturn=updateInfo(erpStockoutstock,erpStockoutstockentryDtos);
		if(isReturn!=null)
		{
			return  isReturn;
		}
		String erpStockoutstockId = IdWorker.get32UUID();
		erpStockoutstock.setFId(erpStockoutstockId);
		erpStockoutstockentryList.forEach(erpStockoutstockentry -> erpStockoutstockentry.setFOutstockid(erpStockoutstockId));
		this.saveBatch(erpStockoutstockentryList, ErpStockoutstockentry.class, ErpStockoutstockentryMapper.class);
		boolean isSuccess = this.save(erpStockoutstock);
		return isSuccess ? erpStockoutstockId : null;
	}

	@Override
	public boolean updateErpStockoutstock(String id, ErpStockoutstock erpStockoutstock, List<ErpStockoutstockentry> erpStockoutstockentryList) {
//		erpStockoutstock.setFId(id);
//		erpStockoutstockentryList.forEach(erpStockoutstockentry -> erpStockoutstockentry.setFOutstockid(id));
//		erpStockoutstockentryMapper.delete(Wrappers.<ErpStockoutstockentry>query().lambda().eq(ErpStockoutstockentry::getFOutstockid, id));
//		this.saveBatch(erpStockoutstockentryList, ErpStockoutstockentry.class, ErpStockoutstockentryMapper.class);
//		return this.updateById(erpStockoutstock);
		return  false;
	}

	public List<ErpStockoutstockentryVo> getErpStockoutstockentryByParentId(String F_OutStockId,String F_WarehouseId){
		return erpStockoutstockentryMapper.getInfo(F_OutStockId,F_WarehouseId);
	}
}
